package com.miaoshapro.controller;

import com.miaoshapro.controller.viewObject.UserVO;
import com.miaoshapro.error.ErrorEnum;
import com.miaoshapro.exception.CommonException;
import com.miaoshapro.response.CommonResponse;
import com.miaoshapro.service.UserService;
import com.miaoshapro.service.model.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Controller("user")
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")    // 解决跨域问题
public class UserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping(value = "/getotp", method = RequestMethod.POST, consumes = CONTENT_TYPE)
    @ResponseBody
    public CommonResponse getOtp(@RequestParam(name = "telphone") String telphone) {
        // 1、生成otp验证码
        Random random = new Random();
        int otp = random.nextInt(999999) + 100000;
        String otpStr = String.valueOf(otp);

        // 2、将otp验证码同用户的手机号进行关联（分布式的做到redis）这里存储到session
        httpServletRequest.getSession().setAttribute(telphone, otpStr);

        // 3、将otp验证码通过手机短信的方式发送给用户
        logger.info("telphone=" + telphone + "&&" + "otp=" + otpStr);

        return CommonResponse.create(null);
    }


    @RequestMapping("/get")
    @ResponseBody
    public CommonResponse getUser(@RequestParam(name = "id") Integer id) throws CommonException {
        UserModel userModel = userService.getUserById(id);
        if (userModel == null) {
            throw new CommonException(ErrorEnum.USER_NOT_FOUND, "用户不存在");
        }
        UserVO userVO = convertFromUserModel(userModel);
        return CommonResponse.create(userVO);
    }


    private UserVO convertFromUserModel(UserModel userModel) {
        if (userModel == null)
            return null;
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = CONTENT_TYPE)
    @ResponseBody
    public CommonResponse register(@RequestParam("telphone") String telphone,
                                   @RequestParam("otpcode") String otpcode,
                                   @RequestParam("password") String password) throws CommonException, UnsupportedEncodingException, NoSuchAlgorithmException {
        // 1、验证otpcode是否正确
        String sessionCode = (String)httpServletRequest.getSession().getAttribute(telphone);
        if (!StringUtils.equals(otpcode, sessionCode)) {
            throw new CommonException(ErrorEnum.PARAMETER_ERROR, "短信验证码填写错误");
        }

        // 2、存储用户注册信息
        UserModel userModel = new UserModel();
        userModel.setTelphone(telphone);
        userModel.setEncrptPassword(this.encrptByMd5(password));
        userModel.setName("admin" + telphone);
        userModel.setGender(Byte.parseByte("0"));
        userModel.setAge(30);
        userModel.setRegisterMode("byphone");

        userService.saveUserInfo(userModel);

        return CommonResponse.create(null);
    }

    public String encrptByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        // 加密字符串
        String encodeStr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return encodeStr;
    }



}
